package hardcode2013;

import com.google.appengine.api.datastore.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AdminServ extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	public static final int resultsPerPage = 50;
	
	public static class LogQueryResult {
		public List<LogProfile> logList;
		public int totalLogs;
	}
	
	public static void logEvent(String user, String event) {
		Entity log = new Entity("Log");
		log.setProperty("datetime", new Date().getTime());
		log.setProperty("username", user);
		log.setProperty("event", event);
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		datastore.put(log);
	}
	
	public static LogQueryResult getEventLogs(int page) {
		LogQueryResult res = new LogQueryResult();
	    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	    Query query = new Query("Log");
	    res.totalLogs = datastore.prepare(query).countEntities(FetchOptions.Builder.withDefaults());
	    query = query.addSort("datetime", Query.SortDirection.DESCENDING);
	    FetchOptions options = FetchOptions.Builder.withLimit(resultsPerPage).offset((page - 1) * resultsPerPage);
	    QueryResultList<Entity> queryResList = datastore.prepare(query).asQueryResultList(options);
	    List<LogProfile> logList = new ArrayList<LogProfile>();
	    for (Entity e : queryResList) {
	    	logList.add(new LogProfile(
	    			KeyFactory.keyToString(e.getKey()),
	    			new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date((Long) e.getProperty("datetime"))),
	    			(String) e.getProperty("username"),
	    			(String) e.getProperty("event")));
	    }
	    res.logList = logList;
	    return res;
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String action = req.getParameter("action");
		if (action == null) {HttpUtil.HomeRedirect(resp); return;}
		
		//--- Deactivate Account --- : Admin
		if (action.equals("deactivate_account")) { //target_username
			//load
			String authKey = req.getParameter("auth_key");			
			String username = SessionUtil.getAuthUsername(req);
			String targetUsername = req.getParameter("target_username");
			boolean isAdmin = (username != null && AccountServ.isAdmin(username));
			
			//check
			if (! SessionUtil.authUser(req, username, authKey))
				{HttpUtil.HomeRedirect(resp); return;}
			else if (! isAdmin)
				{HttpUtil.HomeRedirect(resp); return;}
			else if (! AccountServ.checkAccountExists(targetUsername.trim()))
				{HttpUtil.ExitWithMsg("Target username does not exist.", req, resp); return;}
			Entity account = AccountServ.getAccountEntity(targetUsername.trim());
			if (! (Boolean) account.getProperty("active"))
				{HttpUtil.ExitWithMsg("Target account already deactivated.", req, resp); return;}
			
			//perform
			account.setProperty("active", false);
			DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
			datastore.put(account);
			AdminServ.logEvent(username, "Deactivated Account: " + account.getProperty("username"));
			SessionUtil.setMessage(req, "Account deactivated successfully.");
		}
		
		HttpUtil.FinalRedirect(req, resp);
	}
}
